<template>


    <div class="wrapper">
        <div class="top">
            <div class="top_logo">
                <img src="../assets/mmt.png">
                <p> MomoTalk</p>
            </div>
        </div>

        <div class="change_info">
            <button>修改个人信息</button>
        </div>



        <div class="sidenav">
            <div class="search"> <!---搜索-->
                <input id="search_01" placeholder="搜索">
            </div>

            <ul> <!---对话状态栏--> <!--点击对话li,获取当前conversation_id-->
                <li v-for="item in user_list" @click="toChat(item.conversation_id, item.id)">
                    <div class="content">
                        <img class="li_img" :src="item.avatar_url">
                        <div class="li_center">
                            <div class="li_top">
                                <span class="li_name">{{ item.userName }}</span> <!--UI没做-->
                                <span class="li_time" style="font-size: 1.1vh;">{{ item.created_at }}</span>
                            </div>
                            <div class="li_last">{{ item.content }}</div>
                        </div>
                    </div>
                </li>
            </ul>
        </div>


        <div class="title"> <!--头部框,类似qq的集成功能等，虽然不可能做出来-->
            <div class="person_info">
                <img class="li_img" :src="you.avatar_url">
                <p class="li_name">{{ you.userName }}</p>
            </div>
        </div>


        <div class="chat"> <!---聊天区--> <!--一些发现，base64大于10kb的图似乎就显示不了，jpg会斩断，png会不显示，会不会和他们各自的编码方式有关呢-->
            <ul id="chat">
                <li v-for="(msg, i) in message" :key="i" :class="msg.id === user.id ? 'right' : 'left'">
                    <!--轮询的key相同会产生歧义导致vue报错-->
                    <img :class="msg.id === user.id ? 'img_right' : 'img_left'"
                        :src="msg.id === user.id ? me.avatar_url : you.avatar_url">
                    <div :class="msg.id === user.id ? 'content_right' : 'content_left'">
                        <div :class="msg.id === user.id ? 'name_time_right' : 'name_time_left'">
                            <p>{{ msg.created_at }}</p>
                        </div>
                        <p :class="msg.id === user.id ? 'info_right' : 'info_left'">
                            {{ msg.content }}
                        </p>
                    </div>
                </li>
            </ul>
        </div>

        <div class="bottom"> <!--下方输入框-->
            <div class="top_fuc"> <!--功能按钮-->

            </div>
            <div class="in_out"> <!--输入框，发送-->
                <input class="input_01" id="input_01" placeholder="输入消息...">
                <button class="output_01" @click="sendmessage()">发送</button>
            </div>
        </div>

        <div class="popup">
            <div class="title_1">
                <h2>{{ getPageTitle() }}</h2>
                <button @click="closePopup"
                    style="background-color: transparent; border: none; padding-right: 1vw; font-size: 3vh;"
                    class="close-btn">x</button>
            </div>
            <ul class="settings" v-if="currentPage === 'settings'">
                <li @click="change_avatar()">
                    <span class="li_left">头像</span>
                    <div class="li_right">
                        <img :src="me.avatar_url" style="width: 2.3vw;height: 2.3vw;"></img>
                        <p class="fa fa-caret-right" style="font-size: 1vw;"></p>
                    </div>
                </li>

                <li @click="change_userName()">
                    <span class="li_left">昵称</span>
                    <div class="li_right">
                        <p style="font-size: 1vw;">{{ me.userName }}</p>
                        <p class="fa fa-caret-right" style="font-size: 1vw;"></p>
                    </div>
                </li>

                <li @click="change_sex()">
                    <span class="li_left">性别</span>
                    <div class="li_right">
                        <p style="font-size: 1vw;">{{ me.userSex === 1 ? "男" : "女" }}</p>
                        <p class="fa fa-caret-right" style="font-size: 1vw;"></p>
                    </div>
                </li>

                <li @click="change_password()">
                    <span class="li_left">修改密码</span>
                    <div class="li_right">
                        <p class="fa fa-caret-right" style="font-size: 1vw;"></p>
                    </div>
                </li>

                <li>
                    <a href="https://gitee.com/Xu-zhiyuan0721/front-end--musicplayer">关于我</a>
                </li>
            </ul>

            <!-- 修改昵称页面 -->
            <div class="edit-name-page" v-else-if="currentPage === 'change_userName'">
                <div class="edit-name-container">
                    <div class="edit-name-input-group">
                        <label class="edit-name-label">新昵称</label>
                        <input type="text" v-model="newUserName" class="edit-name-input" placeholder="请输入新昵称">
                    </div>
                    <div class="edit-name-btn-group">
                        <button @click="backToSettings" class="edit-name-cancel-btn">
                            取消
                        </button>
                        <button @click="saveUserName" class="edit-name-save-btn">
                            保存
                        </button>
                    </div>
                </div>
            </div>

            <!-- 修改性别页面 -->
            <div class="edit-sex-page" v-else-if="currentPage === 'change_sex'">
                <div style="padding: 2vw;">
                    <div style="margin-bottom: 2vh;">
                        <label style="display: block; margin-bottom: 1vh; font-size: 1vw;">选择性别</label>
                        <div class="sex-options">
                            <label class="sex-option">
                                <input type="radio" v-model="selectedSex" value="1">
                                <span>男</span>
                            </label>
                            <label class="sex-option">
                                <input type="radio" v-model="selectedSex" value="0">
                                <span>女</span>
                            </label>
                        </div>
                    </div>
                    <div style="display: flex; justify-content: space-around; margin-top: 3vh;">
                        <button @click="backToSettings"
                            style="padding: 0.8vh 2vw; border: none; border-radius: 4px; background-color: #ccc; cursor: pointer;">
                            取消
                        </button>
                        <button @click="saveSex"
                            style="padding: 0.8vh 2vw; border: none; border-radius: 4px; background-color: #4CAF50; color: white; cursor: pointer;">
                            保存
                        </button>
                    </div>
                </div>
            </div>

            <!-- 修改密码页面 -->
            <div class="edit-password-page" v-else-if="currentPage === 'change_password'">
                <div class="edit-name-container">
                    <div class="edit-name-input-group">
                        <label class="edit-name-label">新密码</label>
                        <input type="text" v-model="oldPassword" class="edit-name-input" placeholder="请输入原密码">
                        <input type="text" v-model="newPassword1" class="edit-name-input" placeholder="请输入原密码">
                        <input type="text" v-model="newPassword2" class="edit-name-input" placeholder="请输入原密码">
                    </div>
                    <div class="edit-name-btn-group">
                        <button @click="backToSettings" class="edit-name-cancel-btn">
                            取消
                        </button>
                        <button @click="savePassword" class="edit-name-save-btn">
                            保存
                        </button>
                    </div>
                </div>
            </div>

        </div>


    </div>

</template>

<script>
export default {
    name: 'Login',
    data() {
        return {
            user: {},
            user_list: [],
            message: [],
            me: {},
            you: {},
            conversation_id: '',
            currentPage: 'settings',
            newUserName: '',
            selectedSex:'',
            oldPassword:'',
            newPassword1:'',
            newPassword2:'',
        }
    },
    created() {
        this.user = this.$getSessionStorage('user');
        if (this.user == null) {
            console.log("未登录");
            this.$router.push({
                path: '/login'
            });
            return;
        }
        console.log(this.user.id);

        this.startPolling();          //轮询更新信息，挺蠢的其实

        this.$axios.post('UserController/listUserInfoByUserId', this.$qs.stringify({
            userId: this.user.id
        })).then(response => {
            this.me = response.data;
        }).catch(error => {
            console.error(error);
        });

        this.$axios.post('ConversationController/listContactByUserId', this.$qs.stringify({                //对话栏
            userId: this.user.id
        })).then(response => {
            this.user_list = response.data;
        }).catch(error => {
            console.error(error);
        });
    },
    methods: {

        startPolling() {
            this.pollingTimer = setInterval(() => {
                if (this.conversation_id >= 1) {
                    this.$axios.post('ConversationController/listMessageByConversationId', this.$qs.stringify({
                        conversation_id: this.conversation_id
                    })).then(response => {
                        this.message = response.data;
                        console.log("轮询1次");
                    });
                    this.$axios.post('ConversationController/listContactByUserId', this.$qs.stringify({                //对话栏
                        userId: this.user.id
                    })).then(response => {
                        this.user_list = response.data;
                    }).catch(error => {
                        console.error(error);
                    });
                }
            }, 2000); // 每2秒请求一次
        },
        toChat(conversation_id, id) {
            //进入会话同时获取双方信息
            this.$axios.post('UserController/listUserInfoByUserId', this.$qs.stringify({
                userId: id
            })).then(response => {
                this.you = response.data;
            }).catch(error => {
                console.error(error);
            });



            this.$setSessionStorage('conversation_id', conversation_id);
            this.conversation_id = this.$getSessionStorage('conversation_id');
            this.$axios.post('ConversationController/listMessageByConversationId', this.$qs.stringify({
                conversation_id: conversation_id
            })).then(response => {
                console.log(conversation_id);
                this.message = response.data;

                // 等待DOM更新后再滚动
                this.$nextTick(() => {              //nexttick为渲染完成后执行
                    const messageContainer = document.getElementById('chat');
                    if (messageContainer) {
                        messageContainer.scrollTop = messageContainer.scrollHeight;
                    }
                });
            }).catch(error => {
                console.error(error);
            });
        },

        sendmessage() {
            var content = document.getElementById("input_01").value;
            document.getElementById("input_01").value = null;
            console.log(content);
            this.conversation_id = this.$getSessionStorage('conversation_id');
            this.$axios.post('ConversationController/saveMessage', this.$qs.stringify({
                conversation_id: this.conversation_id,
                id: this.user.id,
                content: content
            })).then(response => {
            }).catch(error => {
                console.error(error);
            });
        },

        // 获取当前页面标题
        getPageTitle() {
            switch (this.currentPage) {
                case 'settings': return '设置中心';
                case 'change_userName': return '修改昵称';
                case 'change_sex': return '修改性别';
                default: return '修改密码';
            }
        },


        //修改个人信息相关
        change_avatar() {
            console.log("change_avatar");
            // 创建一个隐藏的文件输入元素
            const fileInput = document.createElement('input');
            fileInput.type = 'file';
            // 限制只能选择图片类型
            fileInput.accept = 'image/*';

            var previewUrl = "";             //发给后端

            // 监听文件选择事件
            fileInput.onchange = (e) => {
                const file = e.target.files[0];
                if (file) {
                    console.log('选中的图片文件:', file);

                    if (file.size > 1024 * 1024) {
                        alert('图片大小不能超过1MB');
                        return;
                    }

                    // 后续可以在这里处理图片，例如预览或上传
                    // 示例：获取图片预览URL
                    const reader = new FileReader();

                    reader.onload = (event) => {
                        previewUrl = event.target.result;
                        console.log('图片预览URL:', previewUrl);
                    };
                    reader.readAsDataURL(file);
                }
            };
            // 触发文件选择对话框
            fileInput.click();
        },

        backToSettings() {
            this.currentPage = 'settings';
        },

        // 关闭弹窗
        closePopup() {
            const popup = document.querySelector('.popup');
            popup.style.transform = 'translate(200%, 20%)';
            popup.style.pointerEvents = 'none';
            // 重置为设置页面
            this.currentPage = 'settings';
        },

        change_userName() {
            this.currentPage = 'change_userName';
        },

        saveUserName() {
            if (!this.newUserName.trim()) {
                alert('昵称不能为空');
                return;
            }
            this.update_info();
        },

        change_sex() {
            this.currentPage = 'change_sex';
        },

        saveSex(){
            if (!this.selectedSex.trim()) {
                alert('请选择性别');
                return;
            }
            this.update_info();
        },

        change_password() {
            this.currentPage='change_password';
        },

        savePassword(){
            if(this.oldPassword!=this.me.password){
                alert('旧密码错误');
                return;
            }
            if(this.newPassword1!=this.newPassword2){
                alert('两次密码不一致');
                return;
            }
            this.update_info();
        },

        update_info(){
            //调用upgrade
            this.$axios.post('UserController/updateUser', this.$qs.stringify({
                userName:this.newUserName==''? this.me.userName:this.newUserName,
                userSex:this.selectedSex==''? this.me.userSex:this.selectedSex,
                password:this.newPassword==''? this.me.password:this.newPassword,
                id:this.me.id,

            })).then(response => {
            }).catch(error => {
                console.error(error);
            });
        }
    }
}
</script>

<style scoped>
body {
    background-color: rgb(255, 233, 237);
}

.wrapper {
    width: 60vw;
    height: 98vh;
    background-color: rgb(255, 255, 255);
    position: fixed;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    border-radius: 2vh;
}

.wrapper .top {
    width: 100%;
    height: 10vh;
    background-color: rgb(241 157 170);
    border-top-left-radius: 2vh;
    border-top-right-radius: 2vh;
}

.wrapper .top .top_logo {
    display: flex;
    margin-left: 2vw
}

.wrapper .top .top_logo p {
    margin: 0;
    line-height: 10vh;
    /* 让文字垂直居中 */
    color: white;
    font-weight: 700;
    font-size: 3vh;
    margin-left: 1vw;
}

.wrapper .top .top_logo img {
    width: 8vh;
    height: 8vh;
    margin-top: 1vh;
}

.wrapper .change_info {
    position: absolute;
    left: -15vw;
    top: 3vh;
}

.wrapper .change_info button {
    width: 13vh;
    padding: 10px;
    transform: skewX(-10deg);
    color: #30312e;
    border: none;
    border-radius: 8px;
    font-size: 20px;
    cursor: pointer;
    margin-top: 2vh;
    font-weight: bold;
    background-color: aquamarine;
}

.wrapper .sidenav {
    height: 90%;
    width: 14vw;
    position: fixed;
    border-bottom-left-radius: 2vh;
    background-color: rgb(255, 255, 255);
    overflow-x: hidden;

    line-height: 6vh;

    border-right: solid 1px pink;
}

.wrapper .sidenav .search {
    width: 100%;
    height: 6vh;
    border-bottom: solid 1.5px pink;
}

.wrapper .sidenav .search input {
    width: 10vw;
    height: 4vh;
    border-radius: 4vh;
    border: solid 1.5px pink;
    margin-left: 1.8vw;
    text-indent: 15px;
}

.wrapper .sidenav .search input::placeholder {
    font-size: 0.8vw;
}

.wrapper .sidenav ul {
    width: 100%;
    list-style-type: none;
    padding-left: 0;
    margin-left: 0;
    margin: 0;
}

.wrapper .sidenav li {
    height: 6vh;
    line-height: 1vh;
    border-bottom: solid 1px pink;
    margin: 1vh 0.6vw 0 0.6vw;
}

.wrapper .sidenav li:hover {
    border-radius: 1.4vh;
    background-color: rgb(255, 240, 245);
    /*
    border-left: solid 0.5vh rgb(241, 157, 170);  
    */
}

.wrapper .sidenav li .content {
    display: flex;
    align-items: center;
    height: 100%;
    line-height: 2vh;
}

.wrapper .sidenav li .content .li_img {
    height: 5vh;
    width: 5vh;
    border-radius: 50%;
    margin-left: 0.4vw;
    margin-right: 0.6vw;
}

.wrapper .sidenav li .content .li_center {
    display: flex;
    flex-direction: column;
    flex: 1;
    justify-content: center;
    min-width: 0;
}

.wrapper .sidenav li .content .li_top {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.wrapper .sidenav li .content .li_name {
    font-weight: bold;
    font-size: 1.5vh;
    color: #333;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.wrapper .sidenav li .content .li_time {
    font-size: 1.5vh;
    color: #aaa;
    margin-left: 1vw;
    white-space: nowrap;
    margin-right: 0.5vw;
}

.wrapper .sidenav li .content .li_last {
    font-size: 1.2vh;
    color: #666;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    margin-top: 10px
}

.wrapper .title {
    width: 45vw;
    height: 9vh;
    border-bottom: solid 1.5px pink;
    padding-left: 15vw;
    line-height: 5vh;
}

.wrapper .title .person_info {
    display: flex;
    align-items: center;
    font-size: 2vh;
    font-weight: bold;
}

.wrapper .title .person_info img {
    height: 6vh;
    width: 6vh;
    border-radius: 50%;
    margin-left: 0.4vw;
    margin-right: 0.6vw;
    border: solid 2.5px pink;
}

.wrapper .chat {
    width: 46vw;
    height: 67vh;
    margin-left: 14vw;
    margin-top: 0;
}

.wrapper .chat ul {
    list-style-type: none;
    margin: 0;
    padding: 0;
    height: 67vh;
    /* 固定高度，和 .chat 区域一致 */
    overflow-y: auto;
    /* 超出时显示垂直滚动条 */
}

.wrapper .chat ul .left {
    display: flex;
    align-items: flex-start;
    /* 改为顶部对齐，而非居中对齐 */
    margin-bottom: 0vh;
    /* 每条消息每个消息块之间增加间距 */
}

.wrapper .chat ul .left .img_left {
    height: 5vh;
    width: 5vh;
    border-radius: 50%;
    margin-top: 1.9vh;
    /* 微调头像轻微名称时间行轻微对齐 */
    margin-left: 3vh;
}

.wrapper .chat ul .left .content_left {
    margin-top: 2vh;
}

.wrapper .chat ul .left .content_left .name_time_left {
    height: 2vh;
    line-height: 2vh;
}

.wrapper .chat ul .left .content_left .name_time_left {
    display: flex;
    align-items: center;
}

.wrapper .chat ul .left .content_left .name_time_left p {
    margin-left: 1vh;
    font-size: 1.5vh;
}

.wrapper .chat ul .left .content_left .info_left {
    background-color: rgb(236, 207, 207);
    margin-left: 1vh;
    max-width: 40%;
    /* 限制消息内容宽度限制 */
    word-wrap: break-word;
    /* 自动换行 */
    padding: 0.7vh 0.7vh 0.7vh 1.2vh;
    border-radius: 1vh;
    border-top-left-radius: 0;
}

/*********右*********/

.wrapper .chat ul .right {
    display: flex;
    flex-direction: row-reverse;
    /* 头像在右，内容在左 */
    align-items: flex-start;
}

.wrapper .chat ul .right .img_right {
    height: 5vh;
    width: 5vh;
    border-radius: 50%;
    margin-top: 1.9vh;
    margin-right: 3vh;
    /* 头像与内容间距在右侧 */
    margin-left: 0;
}

.wrapper .chat ul .right .content_right {
    margin-top: 2vh;
    display: flex;
    flex-direction: column;
    align-items: flex-end;
    /* 内容右对齐 */
}

.wrapper .chat ul .right .content_right .name_time_right {
    height: 2vh;
    line-height: 2vh;
    display: flex;
    align-items: center;
    justify-content: flex-end;
    /* 右对齐 */
}

.wrapper .chat ul .right .content_right .name_time_right p {
    margin-right: 1vh;
    /* 名称与时间间距在右侧 */
    margin-left: 0;
    font-size: 1.5vh;
    text-align: right;
}

.wrapper .chat ul .right .content_right .info_right {
    background-color: rgb(241, 157, 170);
    /* 右侧气泡颜色可自定义 */
    margin-right: 1vh;
    /* 右侧间距 */
    margin-left: 0;
    padding: 0.7vh 1.2vh 0.7vh 1.2vh;

    border-radius: 1vh;
    border-top-right-radius: 0;

    color: #fff;
    max-width: 40%;
    /* 限制消息内容宽度限制 */
    word-wrap: break-word;
    /* 自动换行 */
}


.wrapper .bottom {
    width: 45vw;
    height: 9vh;
    border-top: solid 1.5px pink;
    padding-left: 15vw;
    line-height: 5vh;
}

.wrapper .bottom .top_fuc {
    height: 5ch;
}

.wrapper .bottom .in_out {
    display: flex;
    align-items: center;
}

.wrapper .bottom .in_out .input_01 {
    width: 37vw;
    height: 5vh;
    border-radius: 3vh;
    background-color: rgb(255 240 245);
    border: solid 1.5px rgb(255 179 217 / 0.5);
    text-indent: 1vw;
    font-size: 2vh;
}

.wrapper .bottom .in_out .input_01::placeholder {
    font-size: 2vh;
    line-height: 5vh;
    color: grey;
}

.wrapper .bottom .in_out .output_01 {
    margin-left: 1vw;
    width: 12vh;
    height: 5vh;
    border-radius: 3vh;
    background-color: rgb(241 157 170);
    border: none;

    font-weight: bold;
    font-size: 2vh;
    line-height: 5vh;
    color: aliceblue;
}

.wrapper .popup {
    position: absolute;
    top: 0;
    left: -22vw;
    z-index: 99999;
    width: 20vw;
    height: 60vh;
    background-color: rgb(181, 202, 255);

    transition: opacity 0.5s ease, transform 0.5s ease;
    transform: translate(200%, 20%);
}

.wrapper .popup .title_1 {
    background-color: #dadada;
    overflow: hidden;
    height: 6vh;
    line-height: 6vh;
    line-height: 2vh;
    display: flex;
    justify-content: space-between;
    position: relative;
}

.wrapper .popup .title_1 .close-btn {
  position: absolute;
  right: 1vw; /* 固定在右侧 */
  top: 50%;
  transform: translateY(-50%); /* 垂直居中按钮 */
}

/* 弹窗显示时添加 show 类 */
.wrapper .popup.show {
    opacity: 1;
    pointer-events: auto;
    transform: translate(200%, 20%);
}

.wrapper .popup .settings {
    width: 100%;
    padding: 0;
    margin: 0;
}

.wrapper .popup .settings li {
    display: flex;
    justify-content: space-between;
    align-items: center;
    list-style-type: none;
    border-bottom: solid 1px rgb(112, 98, 98);
    height: 5vh;
    padding: 0 1vw 0 1vw;
    font-family: Arial, sans-serif;
    color: #333;
}

.wrapper .popup .settings li .li_left {
    font-size: 1vw;
}

.wrapper .popup .settings li .li_right {
    display: flex;
    align-items: center;
    gap: 0.5vw;
    /* 元素间距 */
}


.edit-name-container {
    padding: 2vw;
}

.edit-name-input-group {
    margin-bottom: 2vh;
}

.edit-name-label {
    display: block;
    margin-bottom: 1vh;
    font-size: 1vw;
}

.edit-name-input {
    width: 100%;
    padding: 0.8vh;
    border-radius: 4px;
    border: 1px solid #ccc;
    font-size: 1vw;
    margin-bottom: 1vh;
}

.edit-name-btn-group {
    display: flex;
    justify-content: space-around;
    margin-top: 3vh;
}

.edit-name-cancel-btn {
    padding: 0.8vh 2vw;
    border: none;
    border-radius: 4px;
    background-color: #ccc;
    cursor: pointer;
}

.edit-name-save-btn {
    padding: 0.8vh 2vw;
    border: none;
    border-radius: 4px;
    background-color: #4CAF50;
    color: white;
    cursor: pointer;
}

/* 性别选择样式 */
.sex-options {
  display: flex;
  gap: 2vw;
  margin-top: 1vh;
}

.sex-option {
  display: flex;
  align-items: center;
  gap: 0.5vw;
  font-size: 1vw;
  cursor: pointer;
}

.sex-option input {
  width: 1vw;
  height: 1vw;
}

.wrapper .popup.show {
  opacity: 1;
  pointer-events: auto;
  transform: translate(0, 20%);
}
</style>